|
reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;
Access element
Returns a reference to the element at position n in the vector container.
A similar member function, vector::at, has the same behavior as this operator function, except that vector::at signals if the requested position is out of range by throwing an exception.
Parameters
- n
- Position of an element in the vector.
Notice that the first element has a position of 0, not 1.
Member type size_type is an unsigned integral type.
Return value
The element at the specified position in the vector.
Member types reference and const_reference are the reference types to the elements of the vector container (generally defined as T& and const T& respectively in most storage allocation models).
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
// vector::operator[]
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector<int> myvector (10); // 10 zero-initialized elements
unsigned int i;
vector<int>::size_type sz = myvector.size();
// assign some values:
for (i=0; i<sz; i++) myvector[i]=i;
// reverse vector using operator[]:
for (i=0; i<sz/2; i++)
{
int temp;
temp = myvector[sz-1-i];
myvector[sz-1-i]=myvector[i];
myvector[i]=temp;
}
cout << "myvector contains:";
for (i=0; i<sz; i++)
cout << " " << myvector[i];
cout << endl;
return 0;
}
|
Output:
myvector contains: 9 8 7 6 5 4 3 2 1 0
|
Complexity
Constant.
See also
vector::at | Access element (public member function) |
|